'use client'

import { useEffect, useRef } from 'react'
import mermaid from 'mermaid'

interface MermaidProps {
  chart: string
}

// 尺寸配置
const sizeConfig = {
  small: 'max-w-[400px]',
  medium: 'max-w-[600px]',
  large: 'max-w-[800px]',
  full: 'max-w-full'
}

export default function Mermaid({ chart }: MermaidProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const isRendered = useRef(false)

  // 解析配置并清理图表代码
  const { config, cleanChart } = (() => {
    const config = { size: 'full' as keyof typeof sizeConfig }
    let cleanChart = chart
    
    const configMatch = chart.match(/^\s*\{([^}]+)\}\s*/)
    if (configMatch) {
      try {
        const configStr = `{${configMatch[1]}}`
        const parsedConfig = JSON.parse(configStr.replace(/(\w+):/g, '"$1":'))
        Object.assign(config, parsedConfig)
        cleanChart = chart.replace(configMatch[0], '')
      } catch {
        // 配置解析失败，使用默认值
      }
    }
    
    return { config, cleanChart }
  })()

  useEffect(() => {
    if (!containerRef.current || isRendered.current) return

    mermaid.initialize({
      startOnLoad: true,
      theme: 'default',
      securityLevel: 'loose',
    })

    containerRef.current.textContent = cleanChart
    mermaid.init(undefined, containerRef.current)
    isRendered.current = true
  }, [cleanChart])

  return (
    <div className={`my-4 mx-auto ${sizeConfig[config.size]}`}>
      <div className="bg-gray-50 rounded-lg border p-3">
        <div ref={containerRef} className="mermaid text-center" />
      </div>
    </div>
  )
}